#include "metadata_manager.h"
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>

#define METADATA_VERSION 1
#define DATABASES_FILE "databases.dat"
#define TABLES_FILE "tables.dat"
#define COLUMNS_FILE "columns.dat"
#define INDEXES_FILE "indexes.dat"
#define VIEWS_FILE "views.dat"

// 创建元数据管理器
metadata_manager_t* metadata_manager_create(const char* data_dir) {
    if (!data_dir) return NULL;
    
    metadata_manager_t* meta = calloc(1, sizeof(metadata_manager_t));
    if (!meta) return NULL;
    
    strncpy(meta->data_dir, data_dir, sizeof(meta->data_dir) - 1);
    snprintf(meta->system_dir, sizeof(meta->system_dir), "%s/system", data_dir);
    
    return meta;
}

// 销毁元数据管理器
void metadata_manager_destroy(metadata_manager_t* meta) {
    if (!meta) return;
    
    free(meta->databases);
    free(meta->tables);
    free(meta->columns);
    free(meta->indexes);
    free(meta);
}

// 创建目录
static int create_directory(const char* path) {
    struct stat st = {0};
    if (stat(path, &st) == -1) {
        if (mkdir(path, 0755) == -1) {
            return -1;
        }
    }
    return 0;
}

// 初始化元数据管理器
int metadata_manager_init(metadata_manager_t* meta) {
    if (!meta) return -1;
    
    // 创建必要的目录
    if (create_directory(meta->data_dir) != 0) {
        return -1;
    }
    
    if (create_directory(meta->system_dir) != 0) {
        return -1;
    }
    
    char data_subdir[512];
    snprintf(data_subdir, sizeof(data_subdir), "%s/data", meta->data_dir);
    if (create_directory(data_subdir) != 0) {
        return -1;
    }
    
    // 尝试从磁盘加载元数据
    metadata_load_from_disk(meta);
    
    // 如果没有加载到任何数据库，添加默认数据库
    if (meta->database_count == 0) {
        meta->table_count = 0;
        meta->column_count = 0;
        
        // 添加默认的gudb数据库
        metadata_add_database(meta, "gudb");
        metadata_add_database(meta, "test");
    }
    
    meta->is_initialized = true;
    return 0;
}

// 添加数据库
int metadata_add_database(metadata_manager_t* meta, const char* db_name) {
    if (!meta || !db_name) return -1;
    
    // 检查是否已存在
    if (metadata_database_exists(meta, db_name)) {
        return 0; // 已存在，不重复添加
    }
    
    // 扩展数组
    meta->databases = realloc(meta->databases, (meta->database_count + 1) * sizeof(database_info_t));
    if (!meta->databases) return -1;
    
    database_info_t* db = &meta->databases[meta->database_count];
    memset(db, 0, sizeof(database_info_t));
    
    strncpy(db->name, db_name, sizeof(db->name) - 1);
    snprintf(db->path, sizeof(db->path), "%s/data/%s", meta->data_dir, db_name);
    db->created_time = time(NULL);
    db->is_active = true;
    
    // 创建数据库目录
    create_directory(db->path);
    
    meta->database_count++;
    
    // 保存到磁盘
    metadata_save_to_disk(meta);
    
    return 0;
}

// 检查数据库是否存在
bool metadata_database_exists(metadata_manager_t* meta, const char* db_name) {
    if (!meta || !db_name) return false;
    
    for (uint32_t i = 0; i < meta->database_count; i++) {
        if (meta->databases[i].is_active && 
            strcmp(meta->databases[i].name, db_name) == 0) {
            return true;
        }
    }
    return false;
}

// 列出数据库
int metadata_list_databases(metadata_manager_t* meta, database_info_t** databases, uint32_t* count) {
    if (!meta || !databases || !count) return -1;
    
    // 计算活跃数据库数量
    uint32_t active_count = 0;
    for (uint32_t i = 0; i < meta->database_count; i++) {
        if (meta->databases[i].is_active) {
            active_count++;
        }
    }
    
    if (active_count == 0) {
        *databases = NULL;
        *count = 0;
        return 0;
    }
    
    // 分配结果数组
    database_info_t* result = malloc(active_count * sizeof(database_info_t));
    if (!result) return -1;
    
    uint32_t idx = 0;
    for (uint32_t i = 0; i < meta->database_count; i++) {
        if (meta->databases[i].is_active) {
            result[idx++] = meta->databases[i];
        }
    }
    
    *databases = result;
    *count = active_count;
    return 0;
}

// 添加表
int metadata_add_table(metadata_manager_t* meta, const char* db_name, const char* table_name, 
                      column_info_t* columns, uint32_t column_count) {
    if (!meta || !db_name || !table_name || !columns) return -1;
    
    // 检查数据库是否存在
    if (!metadata_database_exists(meta, db_name)) {
        return -1;
    }
    
    // 检查表是否已存在
    if (metadata_table_exists(meta, db_name, table_name)) {
        return -1; // 表已存在
    }
    
    // 添加表信息
    meta->tables = realloc(meta->tables, (meta->table_count + 1) * sizeof(table_info_t));
    if (!meta->tables) return -1;
    
    table_info_t* table = &meta->tables[meta->table_count];
    memset(table, 0, sizeof(table_info_t));
    
    strncpy(table->database_name, db_name, sizeof(table->database_name) - 1);
    strncpy(table->table_name, table_name, sizeof(table->table_name) - 1);
    snprintf(table->table_path, sizeof(table->table_path), "%s/data/%s/%s.dat", 
             meta->data_dir, db_name, table_name);
    table->column_count = column_count;
    table->row_count = 0;
    table->next_row_id = 1;  // 从1开始编号
    table->created_time = time(NULL);
    table->modified_time = table->created_time;
    table->is_active = true;
    
    meta->table_count++;
    
    // 添加列信息
    for (uint32_t i = 0; i < column_count; i++) {
        columns[i].column_index = i;
        strncpy(columns[i].database_name, db_name, sizeof(columns[i].database_name) - 1);
        strncpy(columns[i].table_name, table_name, sizeof(columns[i].table_name) - 1);
        
        meta->columns = realloc(meta->columns, (meta->column_count + 1) * sizeof(column_info_t));
        if (!meta->columns) return -1;
        
        meta->columns[meta->column_count++] = columns[i];
    }
    
    // 保存到磁盘
    metadata_save_to_disk(meta);
    
    return 0;
}

// 检查表是否存在
bool metadata_table_exists(metadata_manager_t* meta, const char* db_name, const char* table_name) {
    if (!meta || !db_name || !table_name) return false;
    
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            return true;
        }
    }
    return false;
}

// 列出表
int metadata_list_tables(metadata_manager_t* meta, const char* db_name, table_info_t** tables, uint32_t* count) {
    if (!meta || !db_name || !tables || !count) return -1;
    
    // 计算指定数据库中的活跃表数量
    uint32_t active_count = 0;
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active && 
            strcmp(meta->tables[i].database_name, db_name) == 0) {
            active_count++;
        }
    }
    
    if (active_count == 0) {
        *tables = NULL;
        *count = 0;
        return 0;
    }
    
    // 分配结果数组
    table_info_t* result = malloc(active_count * sizeof(table_info_t));
    if (!result) return -1;
    
    uint32_t idx = 0;
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active && 
            strcmp(meta->tables[i].database_name, db_name) == 0) {
            result[idx++] = meta->tables[i];
        }
    }
    
    *tables = result;
    *count = active_count;
    return 0;
}

// 获取表的列信息
int metadata_get_table_columns(metadata_manager_t* meta, const char* db_name, const char* table_name,
                              column_info_t** columns, uint32_t* count) {
    if (!meta || !db_name || !table_name || !columns || !count) return -1;
    
    // 计算匹配的列数量
    uint32_t matching_count = 0;
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0) {
            matching_count++;
        }
    }
    
    if (matching_count == 0) {
        *columns = NULL;
        *count = 0;
        return 0;
    }
    
    // 分配结果数组
    column_info_t* result = malloc(matching_count * sizeof(column_info_t));
    if (!result) return -1;
    
    uint32_t idx = 0;
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0) {
            result[idx++] = meta->columns[i];
        }
    }
    
    *columns = result;
    *count = matching_count;
    return 0;
}

// 保存元数据到磁盘
int metadata_save_to_disk(metadata_manager_t* meta) {
    if (!meta) return -1;
    
    char filepath[512];
    FILE* fp;
    
    // 保存数据库信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, DATABASES_FILE);
    fp = fopen(filepath, "wb");
    if (!fp) return -1;
    
    uint32_t version = METADATA_VERSION;
    fwrite(&version, sizeof(uint32_t), 1, fp);
    fwrite(&meta->database_count, sizeof(uint32_t), 1, fp);
    if (meta->database_count > 0) {
        fwrite(meta->databases, sizeof(database_info_t), meta->database_count, fp);
    }
    fclose(fp);
    
    // 保存表信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, TABLES_FILE);
    fp = fopen(filepath, "wb");
    if (!fp) return -1;
    
    fwrite(&version, sizeof(uint32_t), 1, fp);
    fwrite(&meta->table_count, sizeof(uint32_t), 1, fp);
    if (meta->table_count > 0) {
        fwrite(meta->tables, sizeof(table_info_t), meta->table_count, fp);
    }
    fclose(fp);
    
    // 保存列信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, COLUMNS_FILE);
    fp = fopen(filepath, "wb");
    if (!fp) return -1;
    
    fwrite(&version, sizeof(uint32_t), 1, fp);
    fwrite(&meta->column_count, sizeof(uint32_t), 1, fp);
    if (meta->column_count > 0) {
        fwrite(meta->columns, sizeof(column_info_t), meta->column_count, fp);
    }
    fclose(fp);
    
    // 保存索引信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, INDEXES_FILE);
    fp = fopen(filepath, "wb");
    if (!fp) return -1;
    
    fwrite(&version, sizeof(uint32_t), 1, fp);
    fwrite(&meta->index_count, sizeof(uint32_t), 1, fp);
    if (meta->index_count > 0) {
        fwrite(meta->indexes, sizeof(index_info_t), meta->index_count, fp);
    }
    fclose(fp);
    
    return 0;
}

// 从磁盘加载元数据
int metadata_load_from_disk(metadata_manager_t* meta) {
    if (!meta) return -1;
    
    char filepath[512];
    FILE* fp;
    uint32_t version;
    
    // 加载数据库信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, DATABASES_FILE);
    fp = fopen(filepath, "rb");
    if (fp) {
        if (fread(&version, sizeof(uint32_t), 1, fp) == 1 && version == METADATA_VERSION) {
            if (fread(&meta->database_count, sizeof(uint32_t), 1, fp) == 1 && meta->database_count > 0) {
                meta->databases = malloc(meta->database_count * sizeof(database_info_t));
                if (meta->databases) {
                    fread(meta->databases, sizeof(database_info_t), meta->database_count, fp);
                }
            }
        }
        fclose(fp);
    }
    
    // 加载表信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, TABLES_FILE);
    fp = fopen(filepath, "rb");
    if (fp) {
        if (fread(&version, sizeof(uint32_t), 1, fp) == 1 && version == METADATA_VERSION) {
            if (fread(&meta->table_count, sizeof(uint32_t), 1, fp) == 1 && meta->table_count > 0) {
                meta->tables = malloc(meta->table_count * sizeof(table_info_t));
                if (meta->tables) {
                    size_t read_count = fread(meta->tables, sizeof(table_info_t), meta->table_count, fp);
                    printf("DEBUG: Loading %u tables, read %zu tables, expected size %zu\\n", 
                           meta->table_count, read_count, sizeof(table_info_t));
                    if (read_count != meta->table_count) {
                        // 读取失败，可能是结构体大小不匹配，重置为0
                        printf("DEBUG: Table loading failed, resetting table_count to 0\\n");
                        free(meta->tables);
                        meta->tables = NULL;
                        meta->table_count = 0;
                    } else {
                        printf("DEBUG: Successfully loaded %u tables\\n", meta->table_count);
                        for (uint32_t i = 0; i < meta->table_count; i++) {
                            printf("DEBUG: Table %u: %s.%s (active: %d)\\n", 
                                   i, meta->tables[i].database_name, meta->tables[i].table_name, meta->tables[i].is_active);
                        }
                    }
                }
            }
        }
        fclose(fp);
    }
    
    // 加载列信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, COLUMNS_FILE);
    fp = fopen(filepath, "rb");
    if (fp) {
        if (fread(&version, sizeof(uint32_t), 1, fp) == 1 && version == METADATA_VERSION) {
            if (fread(&meta->column_count, sizeof(uint32_t), 1, fp) == 1 && meta->column_count > 0) {
                meta->columns = malloc(meta->column_count * sizeof(column_info_t));
                if (meta->columns) {
                    fread(meta->columns, sizeof(column_info_t), meta->column_count, fp);
                }
            }
        }
        fclose(fp);
    }
    
    // 加载索引信息
    snprintf(filepath, sizeof(filepath), "%s/%s", meta->system_dir, INDEXES_FILE);
    fp = fopen(filepath, "rb");
    if (fp) {
        if (fread(&version, sizeof(uint32_t), 1, fp) == 1 && version == METADATA_VERSION) {
            if (fread(&meta->index_count, sizeof(uint32_t), 1, fp) == 1 && meta->index_count > 0) {
                meta->indexes = malloc(meta->index_count * sizeof(index_info_t));
                if (meta->indexes) {
                    fread(meta->indexes, sizeof(index_info_t), meta->index_count, fp);
                    meta->index_capacity = meta->index_count;
                }
            }
        }
        fclose(fp);
    }
    
    return 0;
}

// 更新行数统计
int metadata_update_row_count(metadata_manager_t* meta, const char* db_name, const char* table_name, 
                             uint64_t row_count) {
    if (!meta || !db_name || !table_name) return -1;
    
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            meta->tables[i].row_count = row_count;
            meta->tables[i].modified_time = time(NULL);
            metadata_save_to_disk(meta);
            return 0;
        }
    }
    return -1;
}

// 获取表路径
const char* metadata_get_table_path(metadata_manager_t* meta, const char* db_name, const char* table_name) {
    if (!meta || !db_name || !table_name) return NULL;
    
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            return meta->tables[i].table_path;
        }
    }
    return NULL;
}

// 获取下一个行ID
int metadata_get_next_row_id(metadata_manager_t* meta, const char* db_name, const char* table_name) {
    if (!meta || !db_name || !table_name) return -1;
    
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            
            // 获取当前的行ID并递增
            uint64_t current_id = meta->tables[i].next_row_id;
            meta->tables[i].next_row_id++;
            meta->tables[i].modified_time = time(NULL);
            
            // 保存到磁盘
            metadata_save_to_disk(meta);
            
            return (int)current_id;
        }
    }
    return -1;
}

// 获取表的行数
uint64_t metadata_get_table_row_count(metadata_manager_t* meta, const char* db_name, const char* table_name) {
    if (!meta || !db_name || !table_name) return 0;
    
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            return meta->tables[i].row_count;
        }
    }
    return 0;
}

// 删除数据库
int metadata_remove_database(metadata_manager_t* meta, const char* db_name) {
    if (!meta || !db_name) return -1;
    
    // Find and mark database as inactive
    for (uint32_t i = 0; i < meta->database_count; i++) {
        if (meta->databases[i].is_active && 
            strcmp(meta->databases[i].name, db_name) == 0) {
            
            // Mark all tables in this database as inactive first
            for (uint32_t j = 0; j < meta->table_count; j++) {
                if (meta->tables[j].is_active &&
                    strcmp(meta->tables[j].database_name, db_name) == 0) {
                    meta->tables[j].is_active = false;
                }
            }
            
            // Mark database as inactive
            meta->databases[i].is_active = false;
            
            // Save changes to disk
            metadata_save_to_disk(meta);
            
            return 0;
        }
    }
    return -1; // Database not found
}

// 删除表
int metadata_remove_table(metadata_manager_t* meta, const char* db_name, const char* table_name) {
    if (!meta || !db_name || !table_name) return -1;
    
    // Find and mark table as inactive
    for (uint32_t i = 0; i < meta->table_count; i++) {
        if (meta->tables[i].is_active &&
            strcmp(meta->tables[i].database_name, db_name) == 0 &&
            strcmp(meta->tables[i].table_name, table_name) == 0) {
            
            // Mark table as inactive
            meta->tables[i].is_active = false;
            
            // Also mark all columns for this table as inactive by removing them
            for (uint32_t j = 0; j < meta->column_count; j++) {
                if (strcmp(meta->columns[j].database_name, db_name) == 0 &&
                    strcmp(meta->columns[j].table_name, table_name) == 0) {
                    // Remove this column by shifting remaining columns left
                    for (uint32_t k = j; k < meta->column_count - 1; k++) {
                        meta->columns[k] = meta->columns[k + 1];
                    }
                    meta->column_count--;
                    j--; // Recheck this index since we shifted elements
                }
            }
            
            // Save changes to disk  
            metadata_save_to_disk(meta);
            
            return 0;
        }
    }
    return -1; // Table not found
}

// Add a new column to an existing table
int metadata_add_column(metadata_manager_t* meta, const char* db_name, const char* table_name,
                       const column_info_t* column) {
    if (!meta || !db_name || !table_name || !column) return -1;
    
    // Check if table exists
    if (!metadata_table_exists(meta, db_name, table_name)) {
        return -1; // Table doesn't exist
    }
    
    // Check if we have space for a new column
    if (meta->column_count >= meta->column_capacity) {
        // Expand column array
        uint32_t new_capacity = meta->column_capacity ? meta->column_capacity * 2 : 100;
        column_info_t* new_columns = realloc(meta->columns, new_capacity * sizeof(column_info_t));
        if (!new_columns) {
            return -1; // Memory allocation failed
        }
        meta->columns = new_columns;
        meta->column_capacity = new_capacity;
    }
    
    // Check for duplicate column name in the same table
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0 &&
            strcmp(meta->columns[i].column_name, column->column_name) == 0) {
            return -1; // Column already exists
        }
    }
    
    // Add the new column
    meta->columns[meta->column_count] = *column;
    meta->column_count++;
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

int metadata_remove_column(metadata_manager_t* meta, const char* db_name, const char* table_name,
                          const char* column_name) {
    if (!meta || !db_name || !table_name || !column_name) return -1;
    
    // Check if table exists
    if (!metadata_table_exists(meta, db_name, table_name)) {
        return -1; // Table doesn't exist
    }
    
    // Find and remove the column
    bool found = false;
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0 &&
            strcmp(meta->columns[i].column_name, column_name) == 0) {
            
            // Found the column, remove it by shifting remaining columns
            for (uint32_t j = i; j < meta->column_count - 1; j++) {
                meta->columns[j] = meta->columns[j + 1];
            }
            meta->column_count--;
            found = true;
            break;
        }
    }
    
    if (!found) {
        return -1; // Column not found
    }
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

int metadata_modify_column(metadata_manager_t* meta, const char* db_name, const char* table_name,
                          const char* column_name, const column_info_t* new_column_info) {
    if (!meta || !db_name || !table_name || !column_name || !new_column_info) return -1;
    
    // Check if table exists
    if (!metadata_table_exists(meta, db_name, table_name)) {
        return -1; // Table doesn't exist
    }
    
    // Find and modify the column
    bool found = false;
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0 &&
            strcmp(meta->columns[i].column_name, column_name) == 0) {
            
            // Update column properties (keep original database, table, and column name)
            char orig_db[64], orig_table[64], orig_column[64];
            strncpy(orig_db, meta->columns[i].database_name, sizeof(orig_db) - 1);
            strncpy(orig_table, meta->columns[i].table_name, sizeof(orig_table) - 1);
            strncpy(orig_column, meta->columns[i].column_name, sizeof(orig_column) - 1);
            
            // Update with new column info
            meta->columns[i] = *new_column_info;
            
            // Restore original names
            strncpy(meta->columns[i].database_name, orig_db, sizeof(meta->columns[i].database_name) - 1);
            strncpy(meta->columns[i].table_name, orig_table, sizeof(meta->columns[i].table_name) - 1);
            strncpy(meta->columns[i].column_name, orig_column, sizeof(meta->columns[i].column_name) - 1);
            
            found = true;
            break;
        }
    }
    
    if (!found) {
        return -1; // Column not found
    }
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

int metadata_rename_column(metadata_manager_t* meta, const char* db_name, const char* table_name,
                          const char* old_column_name, const char* new_column_name) {
    if (!meta || !db_name || !table_name || !old_column_name || !new_column_name) return -1;
    
    // Check if table exists
    if (!metadata_table_exists(meta, db_name, table_name)) {
        return -1; // Table doesn't exist
    }
    
    // Check if new column name already exists
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0 &&
            strcmp(meta->columns[i].column_name, new_column_name) == 0) {
            return -1; // New column name already exists
        }
    }
    
    // Find and rename the column
    bool found = false;
    for (uint32_t i = 0; i < meta->column_count; i++) {
        if (strcmp(meta->columns[i].database_name, db_name) == 0 &&
            strcmp(meta->columns[i].table_name, table_name) == 0 &&
            strcmp(meta->columns[i].column_name, old_column_name) == 0) {
            
            // Rename the column
            strncpy(meta->columns[i].column_name, new_column_name, 
                   sizeof(meta->columns[i].column_name) - 1);
            meta->columns[i].column_name[sizeof(meta->columns[i].column_name) - 1] = '\0';
            
            found = true;
            break;
        }
    }
    
    if (!found) {
        return -1; // Column not found
    }
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

// 添加索引
int metadata_add_index(metadata_manager_t* meta, const char* db_name, const char* table_name,
                      const index_info_t* index) {
    if (!meta || !db_name || !table_name || !index) return -1;
    
    // Check if table exists
    if (!metadata_table_exists(meta, db_name, table_name)) {
        return -1; // Table doesn't exist
    }
    
    // Check if index already exists
    if (metadata_index_exists(meta, db_name, index->index_name)) {
        return -1; // Index already exists
    }
    
    // Check if we have space for a new index
    if (meta->index_count >= meta->index_capacity) {
        // Expand index array
        uint32_t new_capacity = meta->index_capacity ? meta->index_capacity * 2 : 100;
        index_info_t* new_indexes = realloc(meta->indexes, new_capacity * sizeof(index_info_t));
        if (!new_indexes) {
            return -1; // Memory allocation failed
        }
        meta->indexes = new_indexes;
        meta->index_capacity = new_capacity;
    }
    
    // Add the new index
    meta->indexes[meta->index_count] = *index;
    
    // Ensure the database and table names are set correctly
    strncpy(meta->indexes[meta->index_count].database_name, db_name, 
           sizeof(meta->indexes[meta->index_count].database_name) - 1);
    strncpy(meta->indexes[meta->index_count].table_name, table_name, 
           sizeof(meta->indexes[meta->index_count].table_name) - 1);
    
    meta->indexes[meta->index_count].created_time = time(NULL);
    meta->indexes[meta->index_count].is_active = true;
    
    meta->index_count++;
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

// 删除索引
int metadata_remove_index(metadata_manager_t* meta, const char* db_name, const char* index_name) {
    if (!meta || !db_name || !index_name) return -1;
    
    // Find and remove the index
    bool found = false;
    for (uint32_t i = 0; i < meta->index_count; i++) {
        if (meta->indexes[i].is_active &&
            strcmp(meta->indexes[i].database_name, db_name) == 0 &&
            strcmp(meta->indexes[i].index_name, index_name) == 0) {
            
            // Mark index as inactive
            meta->indexes[i].is_active = false;
            found = true;
            break;
        }
    }
    
    if (!found) {
        return -1; // Index not found
    }
    
    // Save changes to disk
    metadata_save_to_disk(meta);
    
    return 0;
}

// 列出索引
int metadata_list_indexes(metadata_manager_t* meta, const char* db_name, const char* table_name,
                         index_info_t** indexes, uint32_t* count) {
    if (!meta || !db_name || !indexes || !count) return -1;
    
    // Count matching indexes  
    uint32_t matching_count = 0;
    for (uint32_t i = 0; i < meta->index_count; i++) {
        if (meta->indexes[i].is_active &&
            strcmp(meta->indexes[i].database_name, db_name) == 0 &&
            (table_name == NULL || strcmp(meta->indexes[i].table_name, table_name) == 0)) {
            matching_count++;
        }
    }
    
    if (matching_count == 0) {
        *indexes = NULL;
        *count = 0;
        return 0;
    }
    
    // Allocate result array
    index_info_t* result = malloc(matching_count * sizeof(index_info_t));
    if (!result) return -1;
    
    uint32_t idx = 0;
    for (uint32_t i = 0; i < meta->index_count; i++) {
        if (meta->indexes[i].is_active &&
            strcmp(meta->indexes[i].database_name, db_name) == 0 &&
            (table_name == NULL || strcmp(meta->indexes[i].table_name, table_name) == 0)) {
            result[idx++] = meta->indexes[i];
        }
    }
    
    *indexes = result;
    *count = matching_count;
    return 0;
}

// 检查索引是否存在
bool metadata_index_exists(metadata_manager_t* meta, const char* db_name, const char* index_name) {
    if (!meta || !db_name || !index_name) return false;
    
    for (uint32_t i = 0; i < meta->index_count; i++) {
        if (meta->indexes[i].is_active &&
            strcmp(meta->indexes[i].database_name, db_name) == 0 &&
            strcmp(meta->indexes[i].index_name, index_name) == 0) {
            return true;
        }
    }
    return false;
}

// 视图操作函数实现

// 添加视图
int metadata_add_view(metadata_manager_t* meta, const char* db_name, const view_info_t* view) {
    if (!meta || !db_name || !view) return -1;
    
    // 初始化views数组
    if (!meta->views) {
        meta->view_capacity = 64;
        meta->views = malloc(meta->view_capacity * sizeof(view_info_t));
        if (!meta->views) return -1;
        meta->view_count = 0;
    }
    
    // 检查视图是否已存在
    if (metadata_view_exists(meta, db_name, view->view_name)) {
        if (!view->or_replace) {
            return -1; // View exists and OR REPLACE not specified
        }
        // 如果OR REPLACE，则删除现有视图
        metadata_remove_view(meta, db_name, view->view_name);
    }
    
    // 扩展数组如果需要
    if (meta->view_count >= meta->view_capacity) {
        meta->view_capacity *= 2;
        view_info_t* new_views = realloc(meta->views, meta->view_capacity * sizeof(view_info_t));
        if (!new_views) return -1;
        meta->views = new_views;
    }
    
    // 添加新视图
    meta->views[meta->view_count] = *view;
    strncpy(meta->views[meta->view_count].database_name, db_name, sizeof(meta->views[meta->view_count].database_name) - 1);
    meta->views[meta->view_count].created_time = time(NULL);
    meta->views[meta->view_count].modified_time = time(NULL);
    meta->views[meta->view_count].is_active = true;
    meta->view_count++;
    
    return 0;
}

// 删除视图
int metadata_remove_view(metadata_manager_t* meta, const char* db_name, const char* view_name) {
    if (!meta || !db_name || !view_name) return -1;
    
    // 查找并标记视图为非活跃
    bool found = false;
    for (uint32_t i = 0; i < meta->view_count; i++) {
        if (meta->views[i].is_active &&
            strcmp(meta->views[i].database_name, db_name) == 0 &&
            strcmp(meta->views[i].view_name, view_name) == 0) {
            meta->views[i].is_active = false;
            found = true;
            break;
        }
    }
    
    return found ? 0 : -1;
}

// 列出视图
int metadata_list_views(metadata_manager_t* meta, const char* db_name, view_info_t** views, uint32_t* count) {
    if (!meta || !db_name || !views || !count) return -1;
    
    *count = 0;
    *views = NULL;
    
    // 计算活跃视图数量
    uint32_t active_count = 0;
    for (uint32_t i = 0; i < meta->view_count; i++) {
        if (meta->views[i].is_active &&
            strcmp(meta->views[i].database_name, db_name) == 0) {
            active_count++;
        }
    }
    
    if (active_count == 0) return 0;
    
    // 分配内存并复制活跃视图
    *views = malloc(active_count * sizeof(view_info_t));
    if (!*views) return -1;
    
    uint32_t copied = 0;
    for (uint32_t i = 0; i < meta->view_count && copied < active_count; i++) {
        if (meta->views[i].is_active &&
            strcmp(meta->views[i].database_name, db_name) == 0) {
            (*views)[copied++] = meta->views[i];
        }
    }
    
    *count = copied;
    return 0;
}

// 检查视图是否存在
bool metadata_view_exists(metadata_manager_t* meta, const char* db_name, const char* view_name) {
    if (!meta || !db_name || !view_name) return false;
    
    for (uint32_t i = 0; i < meta->view_count; i++) {
        if (meta->views[i].is_active &&
            strcmp(meta->views[i].database_name, db_name) == 0 &&
            strcmp(meta->views[i].view_name, view_name) == 0) {
            return true;
        }
    }
    return false;
}

// 获取视图定义
int metadata_get_view_definition(metadata_manager_t* meta, const char* db_name, const char* view_name,
                                view_info_t* view) {
    if (!meta || !db_name || !view_name || !view) return -1;
    
    for (uint32_t i = 0; i < meta->view_count; i++) {
        if (meta->views[i].is_active &&
            strcmp(meta->views[i].database_name, db_name) == 0 &&
            strcmp(meta->views[i].view_name, view_name) == 0) {
            *view = meta->views[i];
            return 0;
        }
    }
    return -1;
}